import datetime

import requests
from apscheduler.schedulers.blocking import BlockingScheduler


from water import waterapi
from water import models
from water import save2db
from water import common


requests.packages.urllib3.disable_warnings()

PARAM_DATE_FROM = "2023-12-19 08:00:00"
PARAM_DATE_TO = "2024-01-16 18:00:00"


# def my_job(text):
#     str_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#     print(str_now + " " + text)


def schedule_job_run():
    print("schedule_job_run...")
    sched = BlockingScheduler(timezone='Asia/Shanghai')
    # sched.add_job(transfer_data_job, 'interval', minutes=10, args=[])
    # sched.add_job(transfer_data_job, 'interval', hours=1, args=[])
    sched.add_job(transfer_data_job, 'cron', hour=4, minute=20, args=[])
    sched.start()


def transfer_data_job():
    dt_now = datetime.datetime.now()
    dt_date_from = dt_now + datetime.timedelta(days=-1)
    str_date_to = dt_now.strftime("%Y-%m-%d %H:%M:%S")
    str_date_from = dt_date_from.strftime("%Y-%m-%d %H:%M:%S")

    str_token = common.get_access_token()
    print("token is " + str_token)

    models.db.connect()

    api_result = waterapi.get_api_result_大中型水库名录(str_token, str_date_from, str_date_to)
    save2db.save_to_db_大中型水库名录(api_result)

    api_result = waterapi.get_api_result_大中型水库基础信息(str_token, str_date_from, str_date_to)
    save2db.save_to_db_大中型水库基础信息(api_result)

    str_date_from = dt_date_from.strftime("%Y-%m-%d") + " 00:00:00"
    str_date_to = dt_date_from.strftime("%Y-%m-%d") + " 23:59:59"
    api_result = waterapi.get_api_result_河道水位监测数据(str_date_from, str_date_to)
    print(len(api_result))
    save2db.save_to_db_河道水位监测数据(api_result)

    models.db.close()
    print("transfer_data_job 保存完成")


def db_create_table():
    models.db.connect()
    # 创建表 大中型水库名录、大中型水库基础信息
    models.db.drop_tables([models.ReservoirNameList, models.ReservoirBaseInfo, models.RiverWaterLevel])
    models.db.create_tables([models.ReservoirNameList, models.ReservoirBaseInfo, models.RiverWaterLevel])
    models.db.close()
    print("建表完成")


if __name__ == '__main__':
    # db_create_table()
    schedule_job_run()

